<?php
if (!isset($_COOKIE["cur_user"]) or !isset($_POST["courseID"])) {
    echo <<<EOF
<script>
alert("You need to log in!");
url="index.php";
window.location.href=url;
</script>
EOF;
} else {
    setcookie("cur_user", $_COOKIE["cur_user"], time() + 3600);
    setcookie("cur_sid", $_COOKIE["cur_sid"], time() + 3600);
    date_default_timezone_set("PRC");
    $send_date = date("G:i:s,`m-d,`Y");
    $username = $_COOKIE["cur_user"];

    $conn = new PDO("sqlite:storage.db");

    $cid = $_POST["courseID"];
    $sid = $_COOKIE["cur_sid"];
    $text = $_POST["comment-text"];

    $message_length = strlen($text);
    $buffer_size = 500;
    if ($message_length % $buffer_size == 0) {
        $total_index = (int)($message_length / $buffer_size);
    } else {
        $total_index = (int)($message_length / $buffer_size) + 1;
    }

    $sql_command = <<<EOF
insert into comment values (?, ?, ?, ?, ?, ?)
EOF;
    $sql_run = $conn->prepare($sql_command);

    for ($i=1; $i<=$total_index; $i++) {
        $sql_run->execute([
            $cid,
            $sid,
            $send_date,
            substr($text, 0, $buffer_size),
            $i,
            $total_index
        ]);
        $text = substr($text, $buffer_size);
    }
    $conn = null;

    echo <<<EOF
<script>
window.location.href="courseInfo.php?courseID=$cid"
</script>
EOF;
}

